
import { GAME_ID } from "../Platforms/PBPlatform";
import PlatformManager from "../Platforms/PlatformManager";
import { Dictionary } from "../utils/Dictionary";
import { hex_md5 } from "../utils/Md5";



export enum SEND_TYPE {
    HTTP = 1,
    TCP = 2
}

export enum HttpCode {

    kSuccess = 0,             //请求成功

    kTimeout = 10000,         //请求超时

    kUnknow = 10001,          //请求未知

    kSessionTimeout = -8,

}
export const HOST: string = "//pbsdk.game4.cn";//mg1.xuanqii.com
export const TEST_HOST: string = "//pbsdk.game4.cn";//"//114.55.0.49:1008";

/**ws:群黑 */
export const SOCKETHOST: string = "ws://ws.qmmg2.game4.cn";//mg2.xuanqii.com
/**wss: */
export const SOCKETHOST2: string = "wss://ws.qmmg2.game4.cn";//ws.qmmg2.game4.cn
export const TEST_SOCKETHOST: string = "ws://ws.qmmg2.game4.cn";

export function getHost(): string {
    if (CC_DEBUG) {
        return TEST_HOST;
    } else if (CC_BUILD) {
        return HOST;
    }
}
export function getSocketHost(): string {
    if (CC_DEBUG) {

        return SOCKETHOST;
    } else if (CC_BUILD) {
        let protocol = window.location.protocol.split(':')[0];
        if (protocol == "https") {
            return SOCKETHOST2;
        } else {
            return SOCKETHOST;
        }
    }
}

export class NetManager {
    private static _instance: NetManager = null;

    workDic: Dictionary<string, boolean> = new Dictionary();
    isRepeat: boolean = false;
    public static get Instance(): NetManager {
        if (!NetManager._instance) {
            NetManager._instance = new NetManager();
        }
        return NetManager._instance;
    }


    /**
      * get 请求
      * @param url 
      * @param headers 
      * @param params 
      * @param cb 
      */
    doGet(url: string, params: any, cb: Function) {
        if (params) {

            if (url.indexOf("?") == -1) {

                url += "?";
            }

            url += this.getQueryString(params);
        }
        this.doHttp(url, null, "GET", cb);
    }

    /**
     * POST
     * @param url 
     * @param headers 
     * @param params 
     * @param cb 
     */
    doPost(url: string, params: any, cb: Function) {
        let str: string = getHost() + url;
        this.doHttp(str, params, "POST", cb);
    }

    /**
     * 执行http
     * @param url 
     * @param headers 
     * @param params 
     * @param method 
     * @param cb 
     */
    doHttp(url: string, params: any, method: string, cb: Function) {
        if (this.isRepeat) {
            return;
        }

        if (this.workDic.get(url + params) == true) {

            return;
        }
        this.workDic.set(url + params, true);
        let timestamp = cc.sys.now();
        // let authorization: string;
        // if (CC_DEBUG) {
        //     authorization = "abiao";
        // } else if (CC_BUILD) {
        //     authorization = PlatformManager.single.basePlatform.token;
        // }
        let headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "timestamp": timestamp
            // "sign": hex_md5(PlatformManager.single.basePlatform.token + "tests" + timestamp),
        }
        const xhr = new XMLHttpRequest();
        // xhr.responseType = "json";
        xhr.onreadystatechange = this.onReadyStateChange.bind(this, xhr, cb, url, params);
        // xhr.timeout = 30 * 1000;
        xhr.ontimeout = this.onTimeout.bind(this, xhr, url, params);
        xhr.onabort = this.onAbort.bind(this, xhr, url, params);
        xhr.onerror = this.onError.bind(this, xhr, url, cb, params);
        xhr.open(method, url, true);

        if (headers) {
            this.setHttpHeaders(xhr, headers);
        }

        xhr.send(params);
    }

    /**
     * 请求状态
     * @param xhr 
     * @param cb 
     */
    private onReadyStateChange(xhr: XMLHttpRequest, cb: Function, url: string, params: any) {
        console.log("XHR: ", xhr);
        if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
            // let code = HttpCode.kSuccess;

            // const response = xhr.response;

            // if (response && response.code) {

            //     code = response.code;

            // } else {

            //     code = HttpCode.kSuccess;

            // }


            // this.workDic.set(url + params, false);
            // this.notifyCallBack(cb, code, response);
            // this.removeXhrEvent(xhr);
        }
    }

    /**
     * 请求超时触发
     * @param xhr 
     * @param url 
     */
    private onTimeout(xhr: XMLHttpRequest, url: string, params: any) {
        this.workDic.set(url + params, false);
        this.removeXhrEvent(xhr);
        // window.alert("请求超时，请刷新");
        console.log("请求超时", xhr);

    }

    /**
     * 用户中止加载 或 元素时触发
     * @param xhr 
     * @param url 
     */
    private onAbort(xhr: XMLHttpRequest, url: string, params: any) {
        this.workDic.set(url + params, false);
        this.removeXhrEvent(xhr);
        console.log("用户中止加载", xhr);
        // ViewManager.single.PopCommonView("正在请求....");
    }
    /**
     * 监听错误
     * @param xhr 
     * @param url 
     */
    private onError(xhr: XMLHttpRequest, url: string, cb: Function = null, params: any) {
        this.workDic.set(url + params, false);
        this.removeXhrEvent(xhr);
        console.log("请求错误", xhr);
        if (cb) {
            cb({ code: 10000, message: "网络异常" });
        }
        // ViewManager.single.PopCommonView("请求错误....");
    }

    /**
     * 清除xhr事件
     * @param xhr 
     */
    private removeXhrEvent(xhr: XMLHttpRequest) {

        xhr.ontimeout = null;

        xhr.onerror = null;

        xhr.onabort = null;

        // xhr.onreadystatechange = null;
    }

    /**
     * 通知回调
     * @param cb 
     * @param code 
     * @param data 
     */
    private notifyCallBack(cb: Function, code: number, data?: any) {
        if (cb) {
            cb(code, data);
        }
    }

    /**
     * 设置请求头
     * 例 setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     * application/x-www-form-urlencoded
     * multipart/form-data
     * application/json
     * application/xml 和 text/xml
     * @param xhr 
     * @param headers 
     */
    private setHttpHeaders(xhr: XMLHttpRequest, headers: any) {

        for (let key in headers) {

            xhr.setRequestHeader(key, headers[key]);
        }
    }
    /**
   * 将数组转换
   * @param params 
   */
    private getQueryString(params: any) {

        const tmps: string[] = [];

        for (let key in params) {

            tmps.push(`${key}=${params[key]}`);
        }

        return tmps.join("&");
    }




    /**
     * 获取服务器列表
     */
    // public getServerList(): void {


    //     this.doPost("/server/getServerList", null, (code, response) => {
    //         if (code != 0) {
    //             TipsHelp.single.showTxt(response.message);
    //             return;
    //         }
    //         let arr: any[] = response.data;
    //         if (CC_DEBUG) {
    //             console.log("服务器数据：", response.data);
    //         }
    //         // if (arr.length == 0) {
    //         //     arr[0] = { serverId: 1, serverName: "测试", warzone: 1 };
    //         // }
    //         ServerData.getInstance().initdata(arr);
    //         NetManager.Instance.getEnteredServer();
    //         PlatformManager.single.basePlatform.serverid = arr[0].serverId;
    //     });
    // }

    /**获取进入过的服务器 */
    // getEnteredServer() {
    //     let query: string = "";
    //     if (CC_BUILD) {

    //         query = window.location.search.substring(1);

    //     } else if (CC_DEBUG) {
    //         let username = cc.sys.localStorage.getItem("userName");
    //         if (!username) {
    //             username = "7333122211" + Math.random() * 100;
    //         }
    //         cc.sys.localStorage.setItem("userName", username);
    //         query = "username=" + username + "&qhchannel=qunhei_1635405318_7154417_0_2_30_1_18817f5d3062281e4e92badb24836007_90b3ae82b637be39fad3db236531899c_1" + "&serverid=1&time=1342123&isadult=1&nname=张晓珊&unid=test123&flag=test1&showbtn=1&usertag=qunhei&uimg=xxxx";
    //     }
    //     let openId = GameHelp.getQueryVariable('username', query)

    //     let params = GameHelp.getNetParams({ openId: openId });
    //     this.doPost("/server/getEnteredServer", params, (code, response) => {
    //         if (code != 0) {
    //             TipsHelp.single.showTxt(response.message);
    //             return;
    //         }
    //         ServerData.getInstance().initNearServer(response.data);
    //         let nearServers: ServerEntity[] = ServerData.getInstance().nearServers;
    //         if (nearServers != null && nearServers.length > 0) {
    //             PlatformManager.single.basePlatform.serverid = nearServers[0].serverId;
    //         }
    //         GameEvent.eventNode.emit(GameEvent.REQUESTSEVERCOMPLETE_EVENT);
    //     })
    // }



    // /**
    //  * 获取用户登录过的服务器
    //  */
    // public getIntoServer(): Promise<ServerElement[]> {
    //     let url = getHost() + `/server/getIntoServer?openId=${GameData.platform.openId}`;
    //     let promise: Promise<ServerElement[]> = new Promise((resolve, reject) => {
    //         this.doGet(url, undefined, undefined, (code, data) => {
    //             if (data.code != 0) {
    //                 cc.warn(`获取用户登录过的服务器数据失败`)
    //                 resolve([]);
    //                 return;
    //             }

    //             resolve(data.data[0]);
    //         })
    //     })
    //     return promise;
    // }


}
